Class MyClass
{
Public Int DataMember; //By default, accessibility of class data members
//will be private. So I am making it as Public which
//can be accessed outside of the class.
}
在main方法中,
我可以使用new操作符创建该类的实例,为该类 分配内存
并将其基址存储到MyClass类型变量(_myClassObject2)中。< / p >
Static Public void Main (string[] arg)
{
MyClass _myClassObject1 = new MyClass();
_myClassObject1.DataMember = 10;
MyClass _myClassObject2 = _myClassObject1;
_myClassObject2.DataMember=20;
}
Structure MyStructure
{
Public Int DataMember; //By default, accessibility of Structure data
//members will be private. So I am making it as
//Public which can be accessed out side of the structure.
}
Static Public void Main (string[] arg)
{
MyStructure _myStructObject1 = new MyStructure();
_myStructObject1.DataMember = 10;
MyStructure _myStructObject2 = _myStructObject1;
_myStructObject2.DataMember = 20;
}
// Program 1
#include <stdio.h>
class Test {
int x; // x is private
};
int main()
{
Test t;
t.x = 20; // compiler error because x is private
getchar();
return 0;
}
// Program 2
#include <stdio.h>
struct Test {
int x; // x is public
};
int main()
{
Test t;
t.x = 20; // works fine because x is public
getchar();
return 0;
}
// Program 3
#include <stdio.h>
class Base {
public:
int x;
};
class Derived : Base { }; // is equivalent to class Derived : private Base {}
int main()
{
Derived d;
d.x = 20; // compiler error because inheritance is private
getchar();
return 0;
}
// Program 4
#include <stdio.h>
class Base {
public:
int x;
};
struct Derived : Base { }; // is equivalent to struct Derived : public Base {}
int main()
{
Derived d;
d.x = 20; // works fine because inheritance is public
getchar();
return 0;
}
我在class vs struct中发现的另一个方便的事情是,当在程序中实现文件时,如果你想在每一组新的操作上一次又一次地对struct进行一些操作,你需要创建一个单独的函数,并且你需要在从文件中读取struct后传递object of struct,以便对它进行一些操作。
在课堂上,如果你创建了一个函数,每次都对所需的数据进行一些操作,这很简单,你只需要从文件中读取object并调用函数..