【发布时间】:2016-04-10 14:04:54
【问题描述】:
我正在处理的代码:
我有以下代码(main.cpp 中的索引有错误):
示例.hpp:
#ifndef SAMPLE_HPP
# define SAMPLE_HPP
# include <iostream>
# include <string>
class Sample{
public:
Sample(void);
~Sample(void);
void tellname(void) const;
private:
std::string _name;
};
#endif
Sample.cpp:
#include <iostream>
#include "Sample.hpp"
Sample::Sample(void){
this->_name = "testname";
return;
};
Sample::~Sample(void){
return;
}
void Sample::tellname(void) const{
std::cout << "Name : " << this->_name << std::endl;
return;
}
main.cpp
#include "Sample.hpp"
int main(void){
int i;
Sample *test;
test = new Sample[4];
i = 0;
while (i++ < 4) // I know : i++; shouldn't be here
test[i].tellname();
delete [] test;
return 0;
}
如果我编译它,我会得到以下输出:
Name : testname
Name : testname
Name : testname
Name :
我的问题是:
关于最后一行,它调用了一个方法 (void Sample::tellname(void))但来自一个不在表格范围内的实例(test[4] 不存在)。
但是,它仍然调用tellname(),即使它调用它的实例不存在。它只是认为它的_name 字段为空。
这怎么可能?
【问题讨论】:
-
2 个词:未定义的行为。
-
你是对的 - i++ 不应该在那里,这是你问题的根源。改用 for 循环 - for(int i = 0; i
-
对不起,笨蛋,我忘了你问的是“这个”。
标签: c++