如何將繼承的方法分配給物件?,你能解釋一下我的代碼有什么問題嗎?我是新手,所以我想知道是否有更好的方法來做到這一點
int main(){
CalculateData data;
data = data.ReadData(data);//does not let me assign data to the method??
}
其余代碼
#include<string>#include<fstream>#include<iostream>#include<vector>using namespace std;
class File//base class
{
private:
double Size;
public:
vector <double>values;
double GetSize();
void SetSize(double size);
File ReadData(File data);
};
class CalculateData :public File {//inherent from file class
public:
std::vector <double> value;
}
File File::ReadData(File file) {//method of File class
{std::fstream File("Data.txt", std::ios_base::in);
double a;
int counter = 0;
while (File >> a)
{
//printf("%f ", a);
file.values.push_back(a);
counter ;
}
file.SetSize(counter);
cout << "size is " << file.GetSize() << endl;
File.close();
}
return file;
}
uj5u.com熱心網友回復:
坦率地說,這很難提供幫助,因為錯誤只是方法有缺陷的結果。我將使用一個比您的示例更簡單的示例,該示例具有大多數相同的問題:
#include <iostream>
struct Base {
int value;
Base read(Base b) {
b.value = 42;
return b;
};
};
struct Derived : Base{
int values;
};
int main() {
Derived d;
d = d.read(d);
}
直接的問題是編譯器錯誤:
<source>: In function 'int main()':
<source>:17:17: error: no match for 'operator=' (operand types are 'Derived' and 'Base')
17 | d = d.read(d);
| ^
<source>:11:8: note: candidate: 'constexpr Derived& Derived::operator=(const Derived&)'
11 | struct Derived : Base{
| ^~~~~~~
<source>:11:8: note: no known conversion for argument 1 from 'Base' to 'const Derived&'
<source>:11:8: note: candidate: 'constexpr Derived& Derived::operator=(Derived&&)'
<source>:11:8: note: no known conversion for argument 1 from 'Base' to 'Derived&&'
d是 aDerived并read回傳 a Base。它們是不同的型別,除非您在它們之間提供一些轉換,否則您不能將它們分配給彼此。
但是,read將 aBase作為引數(按值)并回傳它只是為了讓呼叫者將其分配給他們呼叫該方法的物件是沒有意義的。如果該方法旨在修改當前物件,那么它應該直接這樣做:
void read() {
value = 42;
}
絕對不需要傳遞 aBase作為引數,無論如何它都會被復制,因為你是按值傳遞的。
代碼中的下一個可疑之處是它Derived有另一個成員,該成員類似于名為 ofBase但未使用的成員。Derived已經確實繼承了value成員Base。它不需要其他values成員。
最后但并非最不重要的一點是,成員的初始化應該在建構式的初始化器串列中進行(如果不使用類內初始化器)。如果初始化很復雜,static可以使用一種方法。因此:
struct Base {
int value;
Base() : value( read_input() ) {}
static int read_input() {
return 42;
}
};
struct Derived : Base {};
int main() {
Derived d;
}
這段代碼的作用與上面相同。由于不清楚其目的Derived是什么,因此可以將其洗掉。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/418326.html
標籤:
