C++基本语法问题(从C#移到C ++)

c++ basic syntax problems(moving from c# to c++) [closed]
2021-06-10
  •  译文(汉语)
  •  原文(英语)

我最近使用过,c#并且希望继续在中进行编程c++.

为什么呢?我喜欢游戏编程,我想学习DirectX游戏中更好的图形

  • 什么时候使用'^'标志?(如Dispatchertimer^ a=ref new Dispatchertimer();)
  • new type()和之间有什么区别ref new type()?什么时候使用哪个?
  • 何时auto在变量或对象(如auto foo = ref new Foo();)之前使用?
  • 我们什么时候必须使用' ::'(like DispatcherTimer::Interval)或' ->'(like a->interval)或' .'(like Timespan.duration)?对于所有这些在c#中,但是现在在c ++中,这有点令人困惑!
速聊1:
每个帖子应该有一个问题.
速聊2:
您是说我必须将每个问题张贴4次吗?
速聊3:
如果它们足够相似以至于彼此相关,则应将它们都包含在帖子中,否则将它们分开.
速聊4:
大声笑-在意识到您是在谈论C ++-cli而不是C ++之前,我已经回答了这个问题.
速聊5:
好吧,他谈论C ++,只是他的意思是C ++ / CLI.
解决过程1

编辑:这是指C ++,而不是C ++-cli,该帖子的标签现在暗示了这个问题.

C#在某些方面基于C ++,但是该语言的一个关键特性是C ++程序员必须处理的许多复杂问题都是在运行时为您处理的,但是解决方案是通用的,因此通常速度较慢.它使C#更加易于学习,并使程序员更容易从中获得良好的结果,而优秀的C ++程序员具有编写更小,更高效和更强大的应用程序的能力.

在C ++中,引用是通过在变量声明中的类型名称后放置"&"表示的.

int i = 0;
int& j = i; // j is now an un-counted ref to i

这些不是C#的引用:它们没有被引用计数,并且不能重新分配.在上面将"j"别名为"i"后,您将无法更改其引用的内容.

int i = 0;
int& j = i;
int k = 2;
j = k; // translates to i = 2

您还必须注意,如果引用的对象消失了,则会引发未定义的行为:

int* i = new int(3); // "i" is actually a pointer, the address of the new integer.
int& j = *i;  // j references the integer to which i points.
j = 2;        // OK: translates to (*i) = 2;
delete i;     // return it to the pool
j = 3;        // UNDEFINED BEHAVIOR: translates to (*i) = 3 but we just released i.

C ++中也没有"ref"关键字,因为没有内置的ref计数类型(但是,您可以使用std :: shared_ptr / std :: weak_ptr实现类似的功能).

"::"是作用域运算符,用于指示"属于作用域",而"."."->"和"->"分别表示"的一个实例的成员"和"由指向的实例的成员".

当您要访问类的常量/静态成员或名称空间的成员,或者需要消除不同名称空间中的相似名称的歧义时,将使用"::".

class Foo {
public:
    void herp();
    enum { Bad = 0, Good = 1 };
    static int open(); // could class with C-standard library 'open' function.
};

// Implement the member "herp" of Foo
void Foo::herp()
{
}

由于foo的"open()"函数被声明为静态函数,因此它不是由成员而是由Class调用的.

// Using "::"
    int quality = Foo::Good;
// Distinguish between 'open' in std vs foo
    int fd = std::open("helloworld.txt");
    int fd = Foo::open();

最后,你问

What is difference between new type() and ref new type()

在C ++中,"新"的意思是"为之分配内存并返回指向它的指针".不会以任何方式对这些数据进行引用计数或管理,因此您有责任确保释放内存,否则会发生所谓的"内存泄漏".考虑:

#include <iostream>

class Foo {
    char m_data[1024 * 1024 * 1024]; // 1Gb of data
public:
    Foo() {
        std::cout << "New Foo at " << (void*)this << std::endl;
    }
    ~Foo() {
        std::cout << "Releasing Foo at " << (void*)this << std::endl;
    }
    void doWork() {
        // imagine the foo is doing some work
    }
};

void makeFooDoWork() {
    static const size_t FOOS_AT_A_TIME = 16;
    Foo* f = new Foo[FOOS_AT_A_TIME];
    for (size_t i = 0; i < FOOS_AT_A_TIME; ++i) {
        foo[i]->doWork();
    }
    /* In C#:
       These objects would call Destroy() as they went out of
       scope making them available for garbage collection.
       In C++:
       allocated objects are YOUR responsibility. Nothing
       happens to them automatically.
     */
     // free [] f;  // <-- what we ought to do here.
}

int main(int argc, char* argv[]) {
    std::cout << "Creating first foo" << endl;
    Foo* f1 = new Foo;
    std::cout << "Releasing it" << endl;
    delete f1;

    for (size_t i = 0; i < 10000000; ++i) {
        makeFooDoWork();
    }
}

在可预见的将来,该程序可能会在大多数计算机上崩溃,因为C ++没有垃圾回收,因此它完全不知道我们没有跟踪分配的对象.


既然问题似乎与C ++ / CLI有关,所以让我添加以下内容:

C ++ / CLI是Microsoft开发的第二种C ++衍生语言.在规定您要询问有关C ++ / CLI的问题时,您需要格外小心,因为它与C ++并非同一事物,而且需要很长时间.除了我不认识任何C ++ / CLI程序员外,我无法谈论C ++ / CLI的普及.我知道Cobol程序员,C#开发人员,Objective-C专家,C程序员甚至ada和业务基础程序员,我有一个咨询顾问,除了LISP以外什么都不做,我有数十个为Microsoft工作的朋友,而且我有各种各样微软认证的web / db / asp开发人员.

但是我所知道的实际上没有人能与C ++ / CLI一起工作-多年前,曾短暂地使用它来尝试开发一些.NET原型,但后来将其用于C#成为了一种选择.

我鼓励您选择C ++或C#,因为您已经知道一些C#可能是最好的选择(例如Unity 3D引擎允许您将C#用作脚本语言);使用C#通过Mono进行跨平台开发是可能的,Microsoft几乎不支持C ++ / CLI.Cf VS2010中没有C / CLI的Intellisense,尽管它于2012年问世.

速聊1:
实际上我想先学习c ++和DirectX以在Windows应用商店中使用,然后再尝试其他事情,我会找到最好的.您认为我是否真的必须继续做我的工作,或者如果我没有,我必须继续做些什么我想使用DirectX做什么?您知道我必须使用DirectX的none.net编译器吗?我很困惑要学习的知识!非常感谢!
速聊2:
该答案可能会有所帮助,建议使用XNA Game Studio,其表达版本是免费的.msdn.microsoft.com/en-us/library/bb200104.aspx 这将使您可以继续使用C#.如果要使用C ++进行开发,则可以免费获取Visual Studio Express.但是,同时学习DirectX和C ++将是一个弯腰:)
速聊3:
但是我听说Microsoft将来将不再支持XNA,当我尝试安装XNA 4.0时,它显示的是兼容性问题,而当我继续安装它时,它会失败.
速聊4:
抱歉,我无济于事:(我只用C ++完成了DX的工作,否则我将C#用于与表格相关的工作和Unity3d
速聊5:
Witch编译器最适合用于DX 11.1 / C ++编程?
解决过程2
  • ^称为"帽子",它基本上是指托管指针,该指针指向被垃圾回收的对象.您只会在.NET Framework(C ++ / CLR)中找到它,它不是C ++标准.
  • ref new type()type再次使用时,它是可以由垃圾收集器处理的引用类.有关更多信息,请访问:http : //www.directxtutorial.com/lessonarticle.aspx?id=0

  • auto关键字指定要声明的变量的类型将自动从其初始值设定项推导出.例如auto a = 3a是的int类型.

  • .->是两个接入运营商,a.b意味着对象的访问部件Ba->b手段存取部件B的对象指向通过.::是范围解析运算符.

但是所有这些都是您应该搜索的基本内容.

I recently used c# and I want to continue programming in c++.

Why? I love game programming and I want to learn DirectX for better graphics in my games

  • When to use '^' sign? (like Dispatchertimer^ a=ref new Dispatchertimer();)
  • What is difference between new type() and ref new type()? When to use which one?
  • When to use auto before a variable or object when making it (like auto foo = ref new Foo();)?
  • when do we have to use '::'(like DispatcherTimer::Interval) or '->'(like a->interval) or '.'(like Timespan.duration)?I was able to use '.' for all of these in c# but now in c++ it is a little confusing!
Talk1:
There should be one question per post.
Talk2:
Do you mean I have to post every question 4 times!?
Talk3:
If they are similar enough to pertain to one another then you should include them both in a post but otherwise keep them separate.
Talk4:
Lol - I'd answered this before realizing you were talking about C++-cli and not C++.
Talk5:
Well, he was talking about C++, only he meant C++/CLI.
Solutions1

EDIT: This refers to C++ and not C++-cli which the post's tags now suggest the question is about.

C# is based on C++ in some ways, but a key feature of the language is that many of the complex issues C++ programmers have to deal with are handled for you by the run time< but the solutions are generic and so generally slower. It makes C# easier to learn and easier for a programmer to start achieving great results from, whereas a good C++ programmer has the ability to write much smaller, more efficient and more powerful applications.

In C++, references are indicated by placing an "&" after the type name in a variable declaration.

int i = 0;
int& j = i; // j is now an un-counted ref to i

These are not C#'s references though: they are not ref-counted, and cannot be re-assigned. Once you have aliased "j" to "i" in the above, you cannot change what it references.

int i = 0;
int& j = i;
int k = 2;
j = k; // translates to i = 2

You also have to be aware that, if the object of your reference goes away, you elicit undefined behavior:

int* i = new int(3); // "i" is actually a pointer, the address of the new integer.
int& j = *i;  // j references the integer to which i points.
j = 2;        // OK: translates to (*i) = 2;
delete i;     // return it to the pool
j = 3;        // UNDEFINED BEHAVIOR: translates to (*i) = 3 but we just released i.

There is also no "ref" keyword in C++, because there is no built-in ref counted type (you can, however, use std::shared_ptr/std::weak_ptr to achieve something similar).

"::" is the scope operator, used to indicate "belonging to the scope" whereas "." and "->" mean "members of an instance of" and "member of an instance pointed to by" respectively.

You'll use "::" when you want to access constant/static members of a class or members of a namespace, or when you need to disambiguate similar names that are in different namespaces.

class Foo {
public:
    void herp();
    enum { Bad = 0, Good = 1 };
    static int open(); // could class with C-standard library 'open' function.
};

// Implement the member "herp" of Foo
void Foo::herp()
{
}

Since foo's "open()" function is declared static, it is not invoked by members but by Class.

// Using "::"
    int quality = Foo::Good;
// Distinguish between 'open' in std vs foo
    int fd = std::open("helloworld.txt");
    int fd = Foo::open();

Lastly, you asked

What is difference between new type() and ref new type()

In C++ "new" means "allocate memory for and return a pointer to". This data is not ref-counted or managed in any way, it is your responsibility to ensure that the memory is freed otherwise you'll incur what is called a "memory leak". Consider:

#include <iostream>

class Foo {
    char m_data[1024 * 1024 * 1024]; // 1Gb of data
public:
    Foo() {
        std::cout << "New Foo at " << (void*)this << std::endl;
    }
    ~Foo() {
        std::cout << "Releasing Foo at " << (void*)this << std::endl;
    }
    void doWork() {
        // imagine the foo is doing some work
    }
};

void makeFooDoWork() {
    static const size_t FOOS_AT_A_TIME = 16;
    Foo* f = new Foo[FOOS_AT_A_TIME];
    for (size_t i = 0; i < FOOS_AT_A_TIME; ++i) {
        foo[i]->doWork();
    }
    /* In C#:
       These objects would call Destroy() as they went out of
       scope making them available for garbage collection.
       In C++:
       allocated objects are YOUR responsibility. Nothing
       happens to them automatically.
     */
     // free [] f;  // <-- what we ought to do here.
}

int main(int argc, char* argv[]) {
    std::cout << "Creating first foo" << endl;
    Foo* f1 = new Foo;
    std::cout << "Releasing it" << endl;
    delete f1;

    for (size_t i = 0; i < 10000000; ++i) {
        makeFooDoWork();
    }
}

This program is likely to crash on most machines for the forseeable future because C++ does not have garbage collection so it is completely unaware that we are not tracking the objects we allocated.


Since it appears the question was actually about C++/CLI, let me add the following:

C++/CLI is a SECOND C++-derived language developed by Microsoft. You need to be careful in stipulating that you are asking questions about C++/CLI because it is NOT the same thing as C++, not by a long stretch. I cannot speak to the popularity of C++/CLI except that I don't know any C++/CLI programmers. I know Cobol programmers, C# developers, Objective-C guys out the wazoo, C programmers even ada and business basic programmers, I have a friend who's consultancy does nothing but LISP, I have dozens of friends who work for Microsoft and I have all kinds of microsoft-certified web/db/asp developers.

But nobody I know actually works with C++/CLI - I used it briefly to try and develop some .NET prototypes many years ago, but dropped it for C# the moment that was an option.

I would encourage you to choose either C++ or C#, and since you already know some C# that may be your best route (e.g. the Unity 3D engine lets you use C# for the scripting language); cross-platform development is possible with C# via Mono, C++/CLI is only, and barely, supported by Microsoft. C.f. There was no Intellisense for C++/CLI in VS2010, although it came back in 2012.

Talk1:
actually I want to learn c++ and DirectX to use in windows store apps at first and then I will try other things and I will find the best.do you think I really have to continue what I am doing or if not what do I have to do?what ever I do I want to use DirectX do you know what none-.net compiler I have to use with DirectX?I'm confused what to learn!thank you so much!
Talk2:
This answer might be helpful, it recommends XNA Game Studio, the expression edition of which is free msdn.microsoft.com/en-us/library/bb200104.aspx This would allow you to continue working in C#. If you want to develop in C++ you can grab Visual Studio Express for free. However, learning DirectX and C++ at the same time is going to be a mind-bender :)
Talk3:
But I heard XNA isn't going to be supported in future by microsoft and when I try to install XNA 4.0 it show's the message of compatibility issue and when I continue installing it fails.no idea?win8 vs2012
Talk4:
Sorry, that I can't help with :( I've only done DX stuff with C++, otherwise I use C# for forms-related stuff and Unity3d
Talk5:
Witch compiler is best to use for DX 11.1/C++ programming?
Solutions2
  • ^ is called a "hat" and it basically means a managed pointer, which points to an object that is garbage collected. You will find it only in .NET framework (C++/CLR), it's not C++ standard.
  • ref new type() is used when type is a reference class, again, that can be handled by a garbage collector. More about it here: http://www.directxtutorial.com/lessonarticle.aspx?id=0

  • auto keyword specifies that the type of the variable that is being declared will be automatically deduced from its initializer. For example auto a = 3 will make a being of int type.

  • . and -> are both access operators, a.b means access member b of object a but a->b means access member b of object pointed by a. :: is a scope resolution operator.

But all those are basic things that you should have googled.

转载于:https://stackoverflow.com/questions/19082225/c-basic-syntax-problemsmoving-from-c-sharp-to-c

本人是.net程序员,因为英语不行,使用工具翻译,希望对有需要的人有所帮助
如果本文质量不好,还请谅解,毕竟这些操作还是比较费时的,英语较好的可以看原文

留言回复
我们只提供高质量资源,素材,源码,坚持 下了就能用 原则,让客户花了钱觉得值
上班时间 : 周一至周五9:00-17:30 期待您的加入