[英]Unexpected out (virtual function returning string)
在以下簡單代碼中,我遇到了一些意外的 output 問題。 output 與基礎 class 配合良好,但由於某種原因,我在派生的 class 上遇到了麻煩。
#include <iostream>
#include <string>
using namespace std;
class vehicle {
public:
string* name;
vehicle() {}
vehicle(const string& inputName) {name = new string(inputName);} //constructor
virtual ~vehicle() {delete name; name = nullptr;} // always make base class destructor virtual
//vehicle(const vehicle& rhs) {*this = rhs; cout << "copy called" << endl;} //copy constructor
vehicle& operator=(const vehicle& rhs) {
cout << "assignment called" << endl;
if(this == &rhs){
return *this;
}
name = new string(*rhs.name);
return *this;
} //assignment operator
virtual string& getName() const {return *name; cout << "base" << endl;} //mark function const if we are not going to make any changes to the object
};
class car : public vehicle {
string *title = new string;
public:
car() : vehicle() {}
car(const string& inputName) : vehicle(inputName) {*title = inputName;}
virtual ~car() {}
virtual string& getName() const {string temp = *title; return temp; cout << "derived" << endl;}
};
int main() {
car test("honda");
string temp;
temp = test.getName();
cout << temp;
return 0;
}
我打算得到以下output:
honda
但我得到:
~weird square boxes~
編輯:
我真正想要完成的是派生的 class 中的以下內容:
virtual string& getName() const {return "Car: " + *name;}
在我因為使用堆作為字符串而發火之前,請知道我只是在這里進行實驗。 據我了解,這在理論上應該可行。
本 function
virtual string& getName() const {string temp = *title; return temp; cout << "derived" << endl;}
調用未定義的行為,因為它返回對本地 object 溫度的引用,該溫度在退出 function 后將不再存在。
您可以像這樣定義 function
virtual const string& getName() const {return *name;}
和
const string& getName() const override { return *title;}
並且return 語句之后的語句沒有效果。
您的其他代碼也有缺點。 例如,復制賦值運算符會產生 memory 泄漏。
或者您需要明確定義 class 汽車的析構函數。
請注意,將數據成員name
和title
聲明為指向std::string
類型對象的指針是沒有意義的。 而是聲明std::string
類型的數據成員。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.