c++ 表达式必须包含类类型 VC_error_code:c2228

c++ 表达式必须包含类类型 VC_error_code:c2228

———

这样的错误一般发生在使用’.’进行访问时,原因可能在于:
  1. 你以为你定义了一个类对象,其实你是声明了一个函数,在编译器看来;
  2. 对类对象指针采用.的方式访问其成员变量;

第一种原因

我们列出会出该错误的代码

class ClassName {
public:
    ClassName(){}
    ClassName(int In_val) {_val=In_val}; 
    void foo() {}
private:
    int _val;
};
int main(int argc, char *argv[]) {
    ClassName x(1);
    x.foo();
    ClassName y();
    y.foo();  // error
    return 0;
}

在上面这个简单例子中” y.foo() “这句话会报错,原因是就是:编译器将” ClassName y(); “当成了一个函数处理了。
类似于下面例子的效果。

class ClassName {
public:
    ClassName() {}
    ClassName(int In_val) { _val = In_val }; //
    void foo() {}
private:
    int _val;
};
int main(int argc, char *argv[]) {
    ClassName x(1);
    x.foo();
    ClassName y();  //被当成声明在函数中的函数了

    ClassName z = y();
    z.foo();    // pass
    //y.foo();  // error
    return 0;
}

ClassName y() {
    return ClassName(233);
}

所以,我们如果要使用无参数的默认构造函数的时候应该如下的写法:

    ClassName ClassVal;
    ClassName ClassVal = ClassName(); // 可能还有其他的写法

第二种原因
class ClassName {
public:
    ClassName(){}
    ClassName(int In_val) {_val=In_val}; //
    void foo() {}
private:
    int _val;
};

int main(int argc, char *argv[]) {
    ClassName *x=new ClassName(233);
    x.foo(); //error
    delete x;
    return 0;
}

错误的原因是,我们应该使用类指针的成员时使用“ -> ”,但是我们用成了 ” . “,导致了编译器报错。

正规写法常见有下面两种

class ClassName {
public:
    ClassName(){}
    ClassName(int In_val) {_val=In_val}; 
    void foo() {}
private:
    int _val;
};

int main(int argc, char *argv[]) {
    ClassName *x=new ClassName(233);
    x->foo();    // 方法一
    (*x).foo();  // 方法二
    delete x;
    return 0;
}
  • 8
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值