int My_Add(int a, int b)
{
return a + b;
}
int My_Sub(int a, int b)
{
return a - b;
}
struct CTest
{
int(*Add)(int, int); //函數指針
int(*Sub)(int, int);
};
int main()
{
struct CTest test;
int ret = 0;
test.Add = My_Add;
test.Sub = My_Sub;
ret = test.Add(3, 5);
printf("%d", ret);
}
c) 比如說這個結構體吧:
struct CTest
{
char ch;
int num;
};
int main()
{
CTest test;
test.num = 1;
printf("%d", test.num);
}
struct A
{
public:
A(){};
virtual void Dynamic()
{
cout << "A" << endl;
}
protected:
void fun();
private:
int m_Data;
};
struct B:public A
{
public:
virtual void Dynamic()
{
cout << "B" << endl;
}
};
int main()
{
A * pa = new B;
pa->Dynamic();
}
拓展部分:再來看一看Java之中類和結構體的區別,來看一個例子:
static void Main(string[] args)
{
int strNumberA = 100;
int strNumberB = strNumberA;//編譯器會先複製strNumberA的值,後賦給strNumberB,會在內存的兩個地方儲存值100
MyVector vA = new MyVector();
MyVector vB = vA;//引用變量的賦值 賦值操作完成後,兩個變量都指向同一內存地址
vA.Value = 100;
Console.WriteLine(vA.Value + " 等於 " + vB.Value);//由於vA和vB指向同一內存地址,所以vB.Value的值也爲100
vB.Value = 200;
Console.WriteLine(vA.Value + " 等於 " + vB.Value);//同理vA.Value =vB.Value
MyStruct structA = new MyStruct();
MyStruct structB = structA; //結構是值類型 賦值操作完成後,兩個結構中的結構信息一致。注意是“結構中的信息”一致。
structA.Value = 100;
structB.Value = 200;
Console.WriteLine(structA.Value + " 不等於 " + structB.Value);//同理vA.Value !=vB.Value
Console.Read();
}
private class MyVector
{
public int Value { get; set; }
}
private struct MyStruct
{
public int Value;
}
最後做一個小小的總結:
(2) 在表示數據量大、邏輯複雜的大對象時,首選class。