can't take address of function unless createing delegate instance - visual-c++

I have a class defined as below:
ref class myClass
{
PictureBox^ pic2;
public:
void setPic2() { pic2 = gcnew PictureBox; }
template<typename UnaryOperator>
void setPic2Click(Form^ x, UnaryOperator op) { pic2->Click += gcnew EventHandler(x, op); }
};
And in my Windows form class:
namespace testProject
{
public ref class Form1 : public System::Windows::Forms::Form
{
void Form1_Load(Object^ sender, EventArgs^ e)
{
rect1.setPic2();
rect1.setPic2Click(this, std::bind1st(std::mem_fun(&Form1::pic2_Click), this));
}
void pic2_Click(Object^ sender, EventArgs^ e)
{
// do something...
}
When compiled, it generated this error which is related to the rect1.setPic2Click call...:
error C3374: can't take address of 'testProject::Form1::pic2_Click' unless creating delegate instance
Basically, I tried to encapsulate the interface of the picturebox by create the instance method setPic2Click. Is this the right approach? Any suggestion how to remedy this error?

Your only mistake is that you're trying to mix managed and unmanaged C++/CLI code in a way that doesn't work (and doesn't make sense).
.NET delegates already have a bound first parameter. All you need is:
class1->setPic2Click(gcnew System::EventHandler(this, &Form1::pic2_Click));
and
void setPic2Click(System::EventHandler^ op) {pic2->Click += op;}

Related

Calling Method/Function outside a Class but on the same namespace in c++/cli

I have a very simple and yet complicated (atleast for me) question on how to call a method/function outside a class but on a same namespace in c++/cli.
I know that you need to create an instance of an object before you can call a method which is inside a class, something like:
namespace Cars {
public ref class MyClass
{
void Honda(int i)
{
//some code
}
}
void Register()
{
MyClass c;
c.Honda(1);
//some code
}
}
But how do I do the opposite? Like how do I call Register() inside the MyClass::Honda function if they are on the same namespace but not on the same class?
I tried Cars::Register() but it gives an error saying that:
Register() is not a member of "Cars".
Edit: I added the actual code that I tried to access the Register() method.
namespace Cars {
public ref class MyClass
{
void Honda(int i)
{
Cars::Register();
}
}
void Register()
{
//some code
}
}
The line Cars::Register(); do not give any error when I save but when I try to rebuild my application it gives the error below:
Error C2039 'Register': is not a member of 'Cars'
Error C3861 'Register': identifier not found
Just to note that when I put Register() inside the MyClass, everything works well (for some reason I just need to put it outside the class)
Thanks!
There are 2 issues in your code:
Missing ; at the end of the definition for ref class MyClass.
Register() should be defined (or at least declared) before calling it.
Fixed version:
namespace Cars
{
// Defintion:
void Register()
{
//some code
}
public ref class MyClass
{
void Honda(int i)
{
Cars::Register();
}
};
}
Or alternatively:
namespace Cars
{
// Declaration:
void Register();
public ref class MyClass
{
void Honda(int i)
{
Cars::Register();
}
};
// Definition:
void Register()
{
//some code
}
}
Note: since you call Register within the same namespace, you can actually drop the Cars:: qualifier, i.e. simply call: Register();. You also keep it of course, if you think it improves readability.

QtConcurrent::run with a virtual class member

So I'm trying to encapsulate a timer class which will handle all of the gory details of multi-threading and timers.
Here's my code:
TimedEvent.h
class TimedEvent : public QObject
{
Q_OBJECT
public:
explicit TimedEvent(QObject *parent = 0);
TimedEvent(const int intervalInMsecs);
virtual void TimeoutWorkProcedure() = 0;
private slots:
void TimeoutWorkThread();
protected:
QTimer *myTimer;
};
TimedEvent.cpp
TimedEvent::TimedEvent(QObject *parent) :
QObject(parent)
{
}
TimedEvent::TimedEvent(const int intervalInMsecs)
{
// Create timer
//
myTimer = new QTimer(this);
// Connect the timeout signal to our virtual callback function
//
connect(myTimer, SIGNAL(timeout()), this, SLOT(TimeoutWorkThread()));
myTimer->start(intervalInMsecs);
}
void TimedEvent::TimeoutWorkThread()
{
QtConcurrent::run(this, &TimedEvent::TimeoutWorkProcedure());
}
The idea was TimedEvent would be a base class and I would be able to create derived classes very easily.
class MyClass : public TimedEvent
{
public:
MyClass( const int timeoutInMsecs );
TimeoutWorkProcedure(){ do some background stuff };
};
The problem is I cannot figure out what to pass to the QtConcurrent::run call. Not sure this is even possible. I could move the QTConcurrent::run call to the derived class, but I anticipate there being several of these derived classes.
Any ideas would be appreciated.
K.
This code:
void TimedEvent::TimeoutWorkThread()
{
QtConcurrent::run(this, &TimedEvent::TimeoutWorkProcedure);
}
is perfectly fine and will do what you expect. It will call an overridden version of TimeoutWorkProcedure.

Inheritance and method invocation through an interface instance

I've been reading "The C# Programming Language. 4th Edition" and found the following code sample:
interface I<T>
{
void F();
}
class Base<U>: I<U>
{
void I<U>.F() {...}
}
class Derived<U,V>: Base<U>, I<V>
{
void I<V>.F() {...}
}
...
I<int> x = new Derived<int,int>();
x.F();
Authors state that after calling x.F() the method in Derived will be invoked, because
"Derived<int,int> effectively reimplements I<int>"
I've checked with C# 4.0 compiler and found that this statement actually invokes the method in Base. Can you explain such behaviour?
Thanks in advance.
edit: here is the working code used for check:
using System;
interface I<T>
{
void F();
}
class Base<U>: I<U>
{
void I<U>.F()
{
Console.WriteLine("F() in Base");
}
}
class Derived<U,V>: Base<U>, I<V>
{
void I<V>.F()
{
Console.WriteLine("F() in Derived");
}
}
public class MainClass
{
public static void Main()
{
I<int> x = new Derived<int,int>();
x.F();
}
}
It outputs "F() in Base", so I don't know where I am wrong.
Because both Base and Derived interface from I.
void I<V>.F() {...} The method may be called/triggered from "Derived" but is executing the method defined in the interface.
void F();

Error CS1061: AppDelegate does not contain a definition for GetNativeField

I'm writting my first iPhone app using mono touch. I have only written a little bit of code, and suddenly, it does not compile anymore, I get this error:
/MyRoute/MainWindow.xib.designer.cs(85,85): Error CS1061: Type xxxx.AppDelegate' does not contain a definition forGetNativeField' and no extension method GetNativeField' of typexxx.AppDelegate' could be found (are you missing a using directive or an assembly reference?) (CS1061) (xxx)
Any idea where this error comes from and how to solve it?
Thanks! :-D
Edited: Added aditional information:
THIS IS THE MAINWINDOW DESIGNER CODE:
namespace GuiaTeleIphone {
// Base type probably should be MonoTouch.Foundation.NSObject or subclass
[MonoTouch.Foundation.Register("AppDelegate")]
public partial class AppDelegate {
private MonoTouch.UIKit.UIWindow __mt_window;
#pragma warning disable 0169
[MonoTouch.Foundation.Connect("window")]
private MonoTouch.UIKit.UIWindow window {
get {
this.__mt_window = ((MonoTouch.UIKit.UIWindow)(this.GetNativeField("window")));
return this.__mt_window;
}
set {
this.__mt_window = value;
this.SetNativeField("window", value);
}
}
}
}
THIS IS THE MAIN.CS:
namespace GuiaTeleIphone
{
public class Application
{
static void Main (string[] args)
{
UIApplication.Main (args);
}
}
// The name AppDelegate is referenced in the MainWindow.xib file.
public partial class AppDelegate : UIApplicationDelegate
{
List<RSSChannel> RemoteChannelsData;
// This method is invoked when the application has loaded its UI and its ready to run
public override bool FinishedLaunching (UIApplication app, NSDictionary options)
{
// If you have defined a view, add it here:
// window.AddSubview (navigationController.View);
window.MakeKeyAndVisible ();
// do things here
return true;
}
}
}
The other partial class of xxxx.AppDelegate is missing or in a different namespace. It specifies the base class.

how to avoid change of class on assigning derived class object to base class object in c# 4?

Hello from C# and OOP newbie.
How can I avoid change of class on assigning derived class object to base class object in c#?
After i run code bellow i get this response
obj1 is TestingField.Two
obj2 is TestingField.Two
I expected that i will lose access to derived methods and properties (which I did) after assigning reference but I did not expect change of class in midcode :S
using System;
namespace TestingField
{
class Program
{
static void Main(string[] args)
{
One obj1 = new One();
Two obj2 = new Two();
obj1 = obj2;
Console.WriteLine("obj1 is {0}", obj1.GetType());
Console.WriteLine("obj2 is {0}", obj2.GetType());
Console.ReadLine();
}
}
class One
{
}
class Two : One
{
public void DoSomething()
{
Console.WriteLine("Did Something.");
}
}
}
While you are right, you will lose access to members declared in the derived type, the object won't suddenly change it's type or implementation. You can access only members declared on the base type, but the implementation of the derived type is used in the case of overriden members, which is the case with GetType, which is a compiler generated method which automatically overrides the base class's implementation.
Extending your example:
class One
{
public virtual void SayHello()
{
Console.WriteLine("Hello from Base");
}
}
class Two : One
{
public void DoSomething()
{
Console.WriteLine("Did Something.");
}
public override void SayHello()
{
Console.WriteLine("Hello from Derived");
}
}
Given:
One obj = new Two();
obj.SayHello(); // will return "Hello from Derived"
GetType is a virtual method gives you the dynamic type of the object.
I think you want the static type of the variable. You can't get this by calling a method on the object referenced by the variable. Instead just write typeof(TypeName), which is typeof(One) or typeof(Two) in your case.
Alternatively in your subclass you can use a new method which hides the original one instead of overriding it:
class One
{
public string MyGetType() { return "One"; }
}
class Two : One
{
public new string MyGetType() { return "Two"; }
}
class Program
{
private void Run()
{
One obj1 = new One();
Two obj2 = new Two();
obj1 = obj2;
Console.WriteLine("obj1.GetType(): " + obj1.GetType());
Console.WriteLine("obj2.GetType(): " + obj2.GetType());
Console.WriteLine("obj1.MyGetType(): " + obj1.MyGetType());
Console.WriteLine("obj2.MyGetType(): " + obj2.MyGetType());
}
}
Result:
obj1.GetType(): Two
obj2.GetType(): Two
obj1.MyGetType(): One
obj2.MyGetType(): Two
You haven't "changed class". The type of the variable obj1 is still One. You have assigned an instance of Two to this variable, which is allowed since Two inherits from One. The GetType method gives you the actual type of the object currently referenced by this variable, not the type of the declared variable itself.

Resources