我正在处理的代码:
我有以下代码(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
示例.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
字段是空的。
这怎么可能?
最佳答案
这只是未定义的行为,C++ 没有强加任何要求,所以“任何事情都可能发生”。您所看到的只是一个巧合,毫无意义:下次运行时它可能会崩溃,显示 nyan cat 等等。
关于c++ - 是否可以从不存在的实例中调用方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34633860/