【发布时间】:2010-09-06 16:52:05
【问题描述】:
如果我想拥有 3 个具有公共字段的类(并且我希望它们是静态的) 他们有一个共同的功能(需要被覆盖,即虚拟)
- 最好的设计是什么?
- 是否需要在头文件中创建接口
然后创建它的 .cpp 文件并从中继承 3 个类? - 静态成员呢?
- 我可以在头文件中声明它们吗?
- 在创建代表接口的头文件时,我必须创建它的.cpp文件吗?
【问题讨论】:
标签: c++ inheritance interface
如果我想拥有 3 个具有公共字段的类(并且我希望它们是静态的) 他们有一个共同的功能(需要被覆盖,即虚拟)
【问题讨论】:
标签: c++ inheritance interface
在头文件中声明类。
这样声明可以在多个源文件(使用#include)之间共享,从而遵守(一个定义规则)。
每个类都有自己的文件是传统的(尽管不是必需的)。为了使其一致且易于查找,您应该在类之后命名文件。所以A 类应该在A.h 中声明并在A.cpp 中定义。
MyInterface.h
class MyInterface
{
protected:
static int X;
static int Y;
static int Z;
public:
// If a class contains virtual functions then you should declare a vritual destructor.
// The compiler will warn you if you don't BUT it will not require it.
virtual ~MyInterface() {} // Here I have declared and defined the destructor in
// at the same time. It is common to put very simplistic
// definitions in the header file. But for clarity more
// complex definitions go in the header file. C++ programers
// dislike the Java everything in one file thing because it
// becomes hard to see the interface without looking at the
// documentaiton. By keeping only the declarations in the
// header it is very easy to read the interface.
virtual int doSomthing(int value) = 0; // Pure virtual
// Must be overridden in derived
};
啊.h
#include "MyInterface.h"
class A: public MyInterface
{
public:
virtual int doSomthing(int value);
};
B.h
#include "MyInterface.h"
class B: public MyInterface
{
public:
virtual int doSomthing(int value);
};
C.h
#include "MyInterface.h"
class C: public MyInterface
{
public:
virtual int doSomthing(int value);
};
现在您在源文件中定义实现:
MyInterface.cpp
#include "MyInterface.h"
// Static members need a definition in a source file.
// This is the one copy that will be accessed. The header file just had the declaration.
int MyInterface::X = 5;
int MyInterface::Y = 6;
int MyInterface::Z = 7;
A.cpp
#include "A.h"
// Define all the methods of A in this file.
int A::doSomthing(int value)
{
// STUFF
}
B.cpp
#include "B.h"
int B::doSomthing(int value)
{
// STUFF
}
C.cpp
#include "C.h"
int C::doSomthing(int value)
{
// STUFF
}
【讨论】:
virtual void printme() = 0;)。现在,如果您有三个具有相同结构的类,您可能(或可能不)喜欢从基类继承它们,原因有几个。一是避免复制代码。另一个主要原因是,您可能希望对派生类中的对象一视同仁,假设您有一辆可以使用的车辆,但该车辆可能是汽车、自行车或飞机。你想使用一辆车,但不介意它到底是哪辆车,所以你创造了
class Vehicle
{
public:
virtual void use() = 0;
};
class Car
: public Vehicle
{
public:
virtual void use();
};
void Car::use()
{
// drive the car
}
比你可以使用汽车作为交通工具,例如
Car myCar;
Vehicle& myVehicle = static_cast< Vehicle& >(myCar);
myVehicle.use(); // drive the car.
这都是基本的 C++ OOP,请在某本书中查找。
【讨论】: