【发布时间】:2016-03-28 11:59:13
【问题描述】:
您好,我在使用 Computer.cpp 中的 set 和 get 方法时遇到问题。我不断收到类型转换错误,例如
从表达式中引用类型“const Case&”的初始化无效 'Case' 或 'Part'、'Part*' 等类型的。
我想要做的是将不同的计算机部件(“部件”是各种具体部件的超类,如机箱、显示器、cpu 等)存储到数组中
Part** m_requiredParts;
这是代码摘录,我在 qt creator 3.6.0 上运行它。
头文件,
Computer.h
#ifndef COMPUTER_H
#define COMPUTER_H
class Computer : public ComputerPlan
{
public:
/**
* @brief Computer default constructor
*/
Computer();
/**
* @brief ~Computer destructor
*/
virtual ~Computer();
// Getters
/**
* @brief getCase retrieves the computer's case information
* @return the computer's Case
*/
virtual const Case& getCase() const;
// Setters
/**
* @brief setCase setter method for Case
* @param computerCase computer's Case
*/
virtual void setCase(const Case &computerCase);
protected:
Part** m_requiredParts;
};
#endif // COMPUTER_H
.CPP 文件
Computer.cpp
#include "Computer.h"
Computer::Computer()
{
m_requiredParts = new Part* [8];
}
Computer::~Computer()
{
}
const Case& Computer::getCase() const
{
const Case& c = (Case&)m_requiredParts[0];
return c;
}
void Computer::setCase(const Case &computerCase)
{
m_requiredParts[0] = (Part*) &computerCase;
//Part**
}
添加一些附加信息,
我在 main.cpp 中通过以下方式设置和获取它们
Computer* computer = new Computer();
computer->setCase(Case("NZXT", Tower));
std::string expected = "Case: NZXT, Case Type: Tower";
std::string actual = std::string(computer->getCase().getPartInformation());
delete computer;
return expected == actual;
【问题讨论】:
-
你怎么称呼
setCase?
标签: c++ arrays pointers casting type-conversion