c++ - 在 C++ 中的类中调用函数?

标签 c++ class

class CBAY_ITEM
{
public:

    string name = enterName();
    string condition = enterCondition();

};

编译时出现4个错误

1.函数调用不能出现在常量表达式中

2.ISO C++ 禁止成员 'name' 的初始化

3.making 'name' static

4.非整数类型 'std::string' 的静态数据成员的类内初始化无效

我做错了什么??

最佳答案

在 C++03 中,您不能在声明成员时初始化成员,除非它们是用常量表达式初始化的静态 const 成员。 C++03 中常量表达式不能包含函数调用。

切换到 C++11(-std=c++11-std=c++0x with gcc 或 clang)或初始化成员CBAY_ITEM 的构造函数。如果您有多个执行公共(public)初始化的构造函数,则可以将公共(public)初始化移至辅助初始化方法。

class CBAY_ITEM {
  std::string name;
  std::string condition;
public:
  CBAY_ITEM() : name(enterName()), condition(enterCondition())
    {}
};

关于c++ - 在 C++ 中的类中调用函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16258315/

相关文章:

c++ - 指向 volatile 数据的指针 (*((volatile uint32_t *)0x40000000))

c++ - 用#ifdef _cplusplus 包装 header 的目的

php - 不同查询返回相同计数值

c++ - 在 lambda 中调用函数时 ADL 失败

c++ - 体验在 Raspberry Pi 上为 PCF8575 I/O 扩展器编写 C 代码

c++ - 在 OpenGL 场景中创建聚光灯

python - 是否可以在 python 中向导入的类添加属性?

python - 处理类内的错误,但在其他脚本中引发?

c++ - 作业帮助 : Prime Number Identifier C++

具有在 2 个不同子类中实现的虚拟方法的 C++ 父类