[英]warning: control reaches end of non-void function - Qt Application
我現在遇到了多態性的問題。 我有一個名為Asset的基類,然后是從該類繼承的3個類 - Bond,Saving和Stock。 Asset類中有一個名為value()的函數,它不是在這個類中實現的,而是在每個派生類中實現的。 我遇到了一些錯誤,並被告知我應該使函數virtual
停止編譯器告訴我我從未實現過該函數。 但現在我收到錯誤Warning: control reaches end of non-void function
我的代碼將無法運行。 我剛剛添加了一個cout << "Testing";
在我的代碼的開頭,仍然沒有。 這是我的Asset類,然后是一個已實現的函數。
Asset.h
#ifndef ASSET_H
#define ASSET_H
#include <QString>
#include <QDate>
class Asset
{
public:
Asset(QString, QDate);
virtual double value() {};
QString getDescription();
QString getType();
protected:
QString type;
QDate date;
private:
QString description;
};
#endif
Stock.cpp value function
double Stock::value()
{
return sharePrice*numShares;
}
我理解將代碼片段拼湊起來很難。 發布所有文件似乎不太合適,有幾個。 但是,如果您想查看它,我已將整個項目鏈接到Google雲端硬盤。 https://drive.google.com/file/d/0B4hZjZFvvaTiWWlhXzF0YWQtcmc/edit?usp=sharing
您的函數有一個意外的實現(定義)。 在你的班級聲明改變
class Asset {
// ...
virtual double value() {};
// ^^ <<<<<<<<<<< You don't want this
// ...
};
至
class Asset {
// ...
virtual double value() = 0;
// ...
};
在類Stock
重寫功能
class Stock : public Asset {
// ...
virtual double value();
// ...
};
其余的實現都像以前一樣好。
在查看您發布的代碼時,我發現Asset::value()
,因為它不會返回任何內容,並且可能是您顯示的錯誤的原因。 您的兩個選擇是使其成為純虛擬
virtual double value() = 0;
或者返回默認值(可能為0)
virtual double value() {return 0.0;}
如果這不能解決您的問題,您應該發布更多代碼。
您的代碼已修復,帶有注釋。
class Currency {
// Never use a floating point type for currency.
// Wrap, for example, Intel's DFP
// http://www.netlib.org/misc/intel/
...
};
class Asset
{
// Since you didn't implement the copy constructor,
// and assignment operator, you must
// disable the copying. Otherwise, you must implement them all,
// and ideally the move constructor as well.
Q_DISABLE_COPY(Asset)
public:
// In Qt, it's idiomatic to pass the complex types via const
// reference, although it's not end of the world not to do so.
// Both are OK, since those "complex" types are cheap to copy.
Asset(const QString &, const QDate &);
/** or **/
Asset(QString, QDate);
// A virtual destructor is necessary for a class that
// can be derived from. Otherwise, inevitable type slicing will
// lead to bugs. Remember: anyone is free to destruct the
// derived class through a pointer to the base class!
virtual ~Asset();
// This is an abstract method, declare it as such.
// It should also be const, since it's a getter.
virtual Currency value() const = 0;
// Getters should be const. The get prefix is redundant.
QString description() const;
QString type() const;
protected:
// Member data should have an agreed-upon prefix,
// to prevent bugs when a local variable is referenced
// instead of a member, and vice-versa.
QString m_type;
QDate m_date;
private:
QString m_description;
};
class Stock : public Asset
{
...
public:
// Q_DECL_OVERRIDE will trigger a compiler error
// if we're not overriding a virtual method.
Currency value() const Q_DECL_OVERRIDE;
...
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.