如果我想要3个类,它们有共同的字段(我希望它们是静态的) 它们有一个共同的功能(需要被覆盖,即虚拟)
答案 0 :(得分:3)
在头文件中声明类。
这样可以在多个源文件(使用#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
};
A.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
}
答案 1 :(得分:1)
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,请在某本书中查阅。