表达式必须具有类类型 但它具有xxx类型

错误一般发生在使用.进行访问时,原因可能在于:

  • 你以为你定义了一个类对象,其实你是声明了一个函数,在编译器看来;

  • 对类对象指针采用.的方式访问其成员变量;
    也包括基本类型变量,错误地使用.

    int a = 10;
    a.foo(); // 显然会提示“错误:表达式必须包含类类型”

  1. 情况 1

    class Test{
    public:
    Test(){ }
    void foo(){ }
    };

    int main(int, char**){
    Test t(); // 编译器会将 t 视为一个函数;
    t.foo(); // 出错,表达式必须包含类类型
    return 0;
    }
    修改方法:

    // 对象的定义,修改为:
    Test t;

    当构造函数中存在一些参数时:

    class Test{
    public:
    Test(int i) {} // 但要避免默认单参构造函数:Test(int i = 0) {}
    ...
    }

    int main(){
    Test t(5);
    ...
    }

  2. 情况 2

    Test* t = new Test(5);
    // 错误访问成员函数的形式:
    t.foo();

    // 正确写法:
    t->foo();

std::string和char*

string->char*:

const char* cstr = str.c_str();

不允许使用不完整的类型

使用git的pull来更新代码后,vs出现这个问题。实际上能够编译通过。原因不明。

posted on 2023-05-06 14:08  FrostyForest  阅读(607)  评论(0)    收藏  举报