在我决定回顾一些所谓的微不足道的例子之前,我以为我对指针有了不错的认识.
我知道的一件事是,在声明一个数组时说:
int arr[2] {3, 5};
Run Code Online (Sandbox Code Playgroud)
arr
将保存数组中第一个元素的值,因此尝试打印that(cout << arr
)显然给出了地址arr[0]
.即使我认为我的程序使用指针它仍然相似.
我的问题是为什么我可以打印h
并bonjour
输出,但我不能这样做p
?
当我h++
再次增加并打印它时,我也会看到它onjour
.指针有何不同char
?
#include <iostream>
#include <string>
int main()
{
char* h = "bonjour";
int k[4]{3, 4, 5, 6};
int * p = k;
std::cout << "Hello, "<< h << "!\n";
}
Run Code Online (Sandbox Code Playgroud) 所以我是C++的新手(以java为背景)我正在经历copy constructor
和destructor
部分,但我仍然没有得到它.我将向您展示的示例来自tutorialpoints.com.所以我有这个代码,但输出只是让我感到困惑.
#include <iostream>
using namespace std;
class Line
{
public:
int getLength( void );
Line( int len ); // simple constructor
Line( const Line &obj); // copy constructor
~Line(); // destructor
private:
int *ptr;
};
// Member functions definitions including constructor
Line::Line(int len)
{
cout << "Normal constructor allocating ptr" << endl;
// allocate memory for the pointer;
ptr = new int;
*ptr = len;
}
Line::Line(const Line &obj)
{
cout << "Copy constructor allocating …
Run Code Online (Sandbox Code Playgroud)