循环通过成员数组给出错误的值
Looping thru member array gives wrong values
我设置了两个类,Dog
和AnotherDog
。 Dog
并不意味着是AnotherDog
的基类。
在AnotherDog
,我有一个Dog
对象。在该Dog
对象中是一个成员数组。当一个AnotherDog
对象调用其Dog
成员,然后让成员循环通过其成员数组时,我得到错误的结果。
#include <iostream>
class Dog
{
private:
int m_NumberOfBarks;
int m_Decibels[];
public:
Dog();
~Dog();
void setBarkDecibels(int decibel1, int decibel2);
void loopDecibels();
};
Dog::Dog() : m_NumberOfBarks(2){}
Dog::~Dog(){}
void Dog::setBarkDecibels(int decibel1, int decibel2){
m_Decibels[0]= decibel1;
m_Decibels[1]= decibel2;
}
void Dog::loopDecibels(){
for(int i=0; i<m_NumberOfBarks; ++i){
std::cout << i << ' ' << m_Decibels[i] << std::endl;
}
}
class AnotherDog
{
private:
Dog m_Dog;
public:
AnotherDog();
~AnotherDog();
Dog getDog();
};
AnotherDog::AnotherDog(){
m_Dog.setBarkDecibels(10, 100);
}
AnotherDog::~AnotherDog(){}
Dog AnotherDog::getDog(){
return m_Dog;
}
int main(){
AnotherDog goodDog;
goodDog.getDog().loopDecibels();
return 0;
}
我希望void Dog::loopDecibels()
打印10
和100
,以及索引。
相反,我得到这个:
0 0
1 4196480
我做错了什么?
我如何实现我想要的结果?
您的程序表现出未定义的行为。
int m_Decibels[];
声明指向 int 的指针,并且不为指针分配任何内存。指针在类构造函数中保持未初始化状态(因为您不初始化它)。当以后你做
m_Decibels[0]= decibel1;
m_Decibels[1]= decibel2;
您正在取消引用此指针,这是禁忌。要解决此问题,您可以使用固定大小的数组:
int m_Decibels[2];
硬币的另一面是,您正在按价值从getDog
返回Dog
实例。在此特定实例上设置分贝时,它对类的原始dog
成员没有影响。若要解决此问题,可能需要通过引用返回对象,如下所示:
Dog& getDog(); // and corresponding change in the definition
相关文章:
- 分段错误当我试图运行程序时出错
- .h 和.cpp文件分离时出错,但仅使用 .h 文件时没有错误.我做错了什么?
- 创建 OpenCV 非自由版本 v4.3 时出错,可折叠.cpp错误 C2039、2605
- 制作时出错,C++"db.c:2127:错误:在"||"标记之前应使用";"
- C++语法错误,编译器不会警告或 int v = func(&v) 出错;
- 在VS2015中访问类成员时运行时错误,但在Linux上未访问时出错
- 如何更改路径以修复错误"./main:加载共享库 libmkl_core.so 时出错?
- 为什么在定义类之前声明类的对象会在友元类中给出错误,而在友元函数中不会出错
- 安装 mply 库时出错.致命错误:gsl/gsl_sf.h:没有这样的文件或目录
- Rcpp/C++/R:比较日期时间矢量与日期时间时出错(错误:"运算符>"的不明确重载)
- 编译特征程序时出错:错误:'seq'不是'Eigen'的成员
- 可能的 GCC 链接器错误会导致将弱符号和局部符号链接在一起时出错
- 非标准语法;使用 '&' 创建指向成员的指针错误,将成员函数分配给向量时出错
- 运算符重载时出错(错误:"运算符<<不匹配(操作数类型为"std::basic_ostream<char>"和"const char [2]")
- 编译类 C++ 中的线程时出错(错误 xthread)
- 加载GLEW库时出错(错误LNK2001)
- 通过函数指针调用函数时出错(错误C2064)
- 编译core.obj时出错:错误LNK2001:未解析的外部符号_harmony_core_init
- 链接c++静态库与android ndk时出错(错误:无法识别文件格式)
- 使用GCC编译游戏时出错.(错误:将"Screen"的含义从"class Screen&q